Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
How to get separate "global" module per instance?

Is it possible get individual "global" module for each instance?

import MyModule from './index.js';

const first = new MyModule();
const second = new MyModule();

// PLEASE SEE EXAMPLE BELOW FOR LOGS

// expect to log for both:
// 1. "in entry: true"
// 2. "in init: true"

// but second module logs:
// 1. "in entry: false"
// 2. "in init: false"

Issue being here that both share globals and 1. instance changes property to false.

What are my options to have in individual globals module per instance?

PS! I have tens of thousands of lines of legacy code. Would be 100x better if I didn't need to change/remove/refactor globals.js contents nor these imports import globals from './globals.js';. Nevertheless, give all your ideas - I need to fix it, even if I need to change a lot.


Code for example above / minimal reproducible example

index.js

import globals from './globals.js';
import init from './init.js';

export default function MyModule (conf) {
  console.log('in entry:', globals.state1);

  init();
}

globals.js

export default {
  state1: true,
};

init.js

import globals from './globals.js';

export default function init () {
  console.log('in init:', globals.state1);
  globals.entry1 = false;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since an object is passed by reference you need to create a copy each time you use globals.

A good way is to export a function like:

/* globals.js */
const globals = { // Maybe wrap the object in Object.freeze() to prevent side effects
    state1: true,
};

export default () => ({ ...globals });

You can then call the function to create a copy each time you need it.

/* init.js */
import getGlobals from './globals.js';

export default function init () {
  const globals = getGlobals();
  console.log('in init:', globals.state1);
  globals.entry1 = false;
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda